/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package teacher;

import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTextArea;

/**
 * 用来开启SercerSocket并接受连接的主服务线程，接受连接后开启子服务线程来处理通信
 *
 * @author Eugene-Forest
 */
public class TeacherThread extends Thread {

    private ServerSocket serverSocket;
    private JLabel hadReadLabel,onlineLabel;

    public TeacherThread(JLabel hadReadLabel,JLabel onlineLabel) {
        //创建主服务线程时同时创建服务套接字（高耦合）
        try {
            this.serverSocket = new ServerSocket(0);
        } catch (Exception e) {
        }
        //初始化组件变量
        this.hadReadLabel=hadReadLabel;
        this.onlineLabel=onlineLabel;
    }

    public int getPort() {
        return serverSocket.getLocalPort();
    }

    @Override
    public void run() {
        try {
            String name;
            //等待学生端连接
            while (true) {
                Socket socket = serverSocket.accept();
                //添加套接字，更新名字列表
                DataCenter.add_socket(socket);
                onlineLabel.setText(String.valueOf(DataCenter.get_sockets_size()));
                //更新名字列表
                //开启子服务线程以处理套接字通信
                Thread subThread = new SubTeacherThread(socket,hadReadLabel,onlineLabel);
                subThread.start();
                //sleep用来阻塞接受套接字的连接，为当前套接字连接所需准备工作提供时间
                sleep(10);
            }
        } catch (Exception e) {
        }
    }

}
